/*
 * LoginServlet.java
 *
 * Created on May 10, 2007, 2:37 AM
 */

package clicktodial.web;

import clicktodial.model.ModelFacade;
import clicktodial.model.Person;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author jkaplan
 * @version
 */
public class LoginServlet extends HttpServlet {
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
    {
        String username = request.getParameter("username");
        request.getSession().setAttribute("username", username);
        
        if (username == null) {
            // logout
            request.getSession().invalidate();
            
            // return to login page
            response.sendRedirect(request.getContextPath());
            return;
        }
        
        ModelFacade mf = (ModelFacade) getServletContext().getAttribute("Model");
        
        Person p = mf.getPerson(username);
        if (p == null) {
            p = new Person(username);
            mf.addPerson(p);
        }
        
        // redirect to main page
        RequestDispatcher dispatcher = request.getRequestDispatcher("/main.jsp");
        dispatcher.forward(request, response);
        //response.sendRedirect(request.getContextPath() + "/main.jsp");
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
